#include "EmotionWindow.h"

#include "EmotionLabelItem.h"

#include <QDebug>
#include <QPainter>
#include <QStyleOption>
#include <CommonUtils.h>

static const int emotionColum = 12;
static const int emotionRow   = 19;

EmotionWindow::EmotionWindow(QWidget* parent)
    : QWidget(parent) {
    setWindowFlags(Qt::FramelessWindowHint | Qt::SubWindow);
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_DeleteOnClose);
    ui.setupUi(this);

    initContronl();
}

EmotionWindow::~EmotionWindow() {}

void EmotionWindow::initContronl() {
    CommonUtils::loadStyleSheet(this, "EmotionWindow");

    ui.emotionWidget->setFixedHeight(32 * emotionRow);
    for (int row = 0; row < emotionRow; row++) {
        for (int colum = 0; colum < emotionColum; colum++) {
            EmotionLabelItem* label = new EmotionLabelItem(this);
            label->setEmotionName(row * emotionColum + colum);

            connect(label, &EmotionLabelItem::emotionClicked, this, &EmotionWindow::addEmotion);
            ui.gridLayout->addWidget(label, row, colum);
        }
    }
}

bool EmotionWindow::eventFilter(QObject* obj, QEvent* event) {
    if (!isActiveWindow()) {
        // 如果点击了其他窗口，关闭当前子窗口
        if (isVisible()) {
            qDebug() << "ObjiectName:" << obj->objectName() << "   setVisible:" << false;
            setVisible(false);
        }
    }
    return QWidget::eventFilter(obj, event);
}
void EmotionWindow::addEmotion(int emotionNum) {
    hide();
    emit signalEmotionWindowHide();
    emit signalEmotionItemClicked(emotionNum);
}

void EmotionWindow::paintEvent(QPaintEvent* event) {
    QStyleOption opt;
    opt.init(this);

    QPainter painter(this);

    style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);

    __super::paintEvent(event);
}

void EmotionWindow::focusOutEvent(QFocusEvent* event) {
    QWidget::focusOutEvent(event);

    // 在窗口失去焦点时执行关闭窗口的操作
    // hide();
}